package logic

import (
	"MyBlogv2/blog-common/HttpCode"
	"MyBlogv2/blog-common/helper"
	"MyBlogv2/blog-common/models"
	"MyBlogv2/blog-common/oss"
	"bytes"
	"context"
	"path"

	"MyBlogv2/Servers/UserAction/internal/svc"
	"MyBlogv2/Servers/UserAction/userAction"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateAvatarLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateAvatarLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateAvatarLogic {
	return &UpdateAvatarLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateAvatarLogic) UpdateAvatar(in *UserAction.UpdateAvatarRequest) (*UserAction.UpdateAvatarResponse, error) {
	userId := int(in.UserId)
	filename := in.Filename
	ext := path.Ext(filename)
	objectName := helper.GetUUID() + ext
	filePath := in.Avatar
	file := bytes.NewReader(filePath)
	uploadFilePath, err := oss.UploadFile(objectName, file)
	if err != nil {
		return &UserAction.UpdateAvatarResponse{
			Code: int64(HttpCode.FILE_UPLOAD_ERROR),
		}, nil
	}
	models.Db.Model(new(models.User)).Where("id = ?", userId).Update("avatar", uploadFilePath)
	return &UserAction.UpdateAvatarResponse{
		Code: int64(HttpCode.SUCCESS),
		Data: uploadFilePath,
	}, nil
}
